<?php

namespace backend\modules\kingdee\controllers;

use common\business\EhrHelper;
use common\business\task\TaskService;
use common\consts\Consts;
use common\models\Employee;
use common\models\kingdee\HrPersonPhoto;
use common\models\qywx\QywxUser;
use Yii;
use common\models\kingdee\Person;
use common\models\kingdee\PersonSearch;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * PersonController implements the CRUD actions for Person model.
 */
class PersonController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Person models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PersonSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }


    /**
     * @param $boolVal boolean
     * @return string
     */
    protected function getSyncStatusStr($boolVal){
        return $boolVal ? Yii::t('app', 'Synced') : Yii::t('app', 'Not Synced');
    }

    /**
     * Displays a single Person model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        $kdSyncStatus = false;
        $employeeStatus = false;
        $qywxSyncStatus = false;

        $model = Person::findOne($id);
        if (!$model){
            return $this->render('view', [
                'model' => null,
                'employee' => null,
                'qywx_user' => null,
                'imageData' => Url::to("@web/images/male_unknown.jpg"),
                'kdSyncStatus' => $kdSyncStatus,
                'kdSyncStatusStr' => $this->getSyncStatusStr($kdSyncStatus),
                'employeeSyncStatus' => $kdSyncStatus,
                'employeeSyncStatusStr' => $this->getSyncStatusStr($employeeStatus),
                'qywxSyncStatus' => $kdSyncStatus,
                'qywxSyncStatusStr' => $this->getSyncStatusStr($qywxSyncStatus),
            ]);
        }

        $kdSyncStatus = true;

        $photoImage = HrPersonPhoto::findOne([
            'FPERSONID' => $model->FID,
        ]);
        if (!$photoImage){
            $imageName = $model->FGENDER == Consts::GENDER_MALE ? 'male_unknown.jpg' : 'female_unknown.jpg';
            $imageData = Url::to("@web/images/$imageName");
        }
        else {
            $imageData = EhrHelper::getPersonPhoto($photoImage);
        }

        $employee = Employee::findOne([
            'number' => $model->FNUMBER,
        ]);
        if (!$employee){
            return $this->render('view', [
                'model' => $model,
                'employee' => null,
                'qywx_user' => null,
                'imageData' => $imageData,
                'kdSyncStatus' => $kdSyncStatus,
                'kdSyncStatusStr' => $this->getSyncStatusStr($kdSyncStatus),
                'employeeSyncStatus' => $kdSyncStatus,
                'employeeSyncStatusStr' => $this->getSyncStatusStr($employeeStatus),
                'qywxSyncStatus' => $kdSyncStatus,
                'qywxSyncStatusStr' => $this->getSyncStatusStr($qywxSyncStatus),
            ]);
        }
        $employeeStatus = true;

        $qywx_user = QywxUser::findOne([
            'number' => $model->FNUMBER,
        ]);
        if(!$qywx_user){
            return $this->render('view', [
                'model' => $model,
                'employee' => $employee,
                'qywx_user' => null,
                'imageData' => $imageData,
                'kdSyncStatus' => $kdSyncStatus,
                'kdSyncStatusStr' => $this->getSyncStatusStr($kdSyncStatus),
                'employeeSyncStatus' => $kdSyncStatus,
                'employeeSyncStatusStr' => $this->getSyncStatusStr($employeeStatus),
                'qywxSyncStatus' => $kdSyncStatus,
                'qywxSyncStatusStr' => $this->getSyncStatusStr($qywxSyncStatus),
            ]);
        }
        $qywxSyncStatus = true;

        return $this->render('view', [
            'model' => $model,
            'employee' => $employee,
            'qywx_user' => $qywx_user,
            'imageData' => $imageData,
            'kdSyncStatus' => $kdSyncStatus,
            'kdSyncStatusStr' => $this->getSyncStatusStr($kdSyncStatus),
            'employeeSyncStatus' => $kdSyncStatus,
            'employeeSyncStatusStr' => $this->getSyncStatusStr($employeeStatus),
            'qywxSyncStatus' => $kdSyncStatus,
            'qywxSyncStatusStr' => $this->getSyncStatusStr($qywxSyncStatus),
        ]);
    }

    /**
     * Creates a new Person model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Person();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->FID]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Person model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->FID]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Person model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Person model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Person the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Person::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionJsonAll($q){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        if (!$q) {
            return $out;
        }

        $data = Person::find()
            ->select('FID as id, FNAME_L2 as text')
            ->andFilterWhere(['like', 'FNAME_L2', $q])
//            ->orderBy([
//                'FID' => SORT_ASC,
//            ])
            ->limit(50)
            ->asArray()
            ->all();

        $out['results'] = array_values($data);

        return $out;
    }

    public function actionSyncToQywx($id){
        $requestData = ['hr_id' => $id];
        $result = (new TaskService())->createTask(Consts::TASK_TYPE_EMPLOYEE_TO_QYWX, 'qywx', Consts::NO, Json::encode($requestData));
        if ($result->isSuccess){
            Yii::$app->getSession()->setFlash('success',  $result->message);
            return $this->redirect(['/task/index']);
        }
        else {
            Yii::$app->getSession()->setFlash('error', $result->getMessage());
            return $this->redirect(['index']);
        }
    }
}
